#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

typedef struct Node {
    int data;         
    struct Node *next;  
} Node;


typedef struct {
    Node *top; 
} LinkedStack;

// 初始化链栈
void initStack(LinkedStack *stack) {
    stack->top = NULL; 
}

int isEmpty(LinkedStack *stack) {
    return stack->top == NULL;
}


void push(LinkedStack *stack, int value) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("失败 %d\n", value);
        return;
    }
    newNode->data = value;
    newNode->next = stack->top; 
    stack->top = newNode;     
    printf("把  %d 进栈\n", value);
}


int pop(LinkedStack *stack) {
    if (isEmpty(stack)) {
        printf("栈空\n");
        exit(EXIT_FAILURE);
    }
    Node *temp = stack->top;     
    int popped_element = temp->data; 
    stack->top = stack->top->next;  
    free(temp);                    
    return popped_element;
}

int top(LinkedStack *stack) {
    if (isEmpty(stack)) {
        printf("栈空\n");
        exit(EXIT_FAILURE);
    }
    return stack->top->data;
}

int main() {
    SetConsoleOutputCP(65001);
    
    LinkedStack stack;

    initStack(&stack);

    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);
    printf("栈顶元素: %d\n", top(&stack));
    printf("出栈元素: %d\n", pop(&stack));
    printf("栈顶元素: %d\n", top(&stack));

    return 0;
}
